//
//  GKNetworkTools.m
//

#import "GKNetworkingManager.h"
#import <AFNetworking/AFNetworking.h>
#import <AFNetworking/AFNetworkActivityIndicatorManager.h>
#import <AFNetworking.h>

@implementation GKUploadParams

@end
@interface GKNetworkingManager ()

@end
static NSMutableArray *tasks;
static AFHTTPSessionManager *manager;

typedef NS_ENUM(NSUInteger, GKRequestType) {
    GKRequestTypeGet,
    GKRequestTypePost
};
@implementation GKNetworkingManager
- (instancetype) init {
    NSLog(@"Use \"sharedManager\" to create Manager instance.");
    return nil;
}
+ (instancetype)sharedManager
{
    static id _instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}

+(NSMutableArray *)tasks{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tasks = [[NSMutableArray alloc] init];
    });
    return tasks;
}

+ (AFHTTPSessionManager *)getAFNManager{
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[AFHTTPSessionManager alloc]initWithBaseURL:[NSURL URLWithString:V2HTTPBaseUrl]];
        manager.requestSerializer.timeoutInterval = 10;
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",@"text/plain", nil];
    });
    return manager;
}


+ (NSURLSessionDataTask *)get:(NSString *)url
                       params:(NSDictionary *)params
                      success:(GKResponseSuccess)success
                      failure:(GKResponseFailure)failure
{

    return [self requestType:GKRequestTypeGet url:url params:params success:success failure:failure];
}



+ (NSURLSessionDataTask *)post:(NSString *)url
                        params:(NSDictionary *)params
                       success:(GKResponseSuccess)success
                       failure:(GKResponseFailure)failure;
{

    return [self requestType:GKRequestTypePost url:url params:params success:success failure:failure];

}
+ (NSURLSessionDataTask *)requestType:(GKRequestType)type
                                  url:(NSString *)url
                               params:(NSDictionary *)params
                              success:(GKResponseSuccess)success
                              failure:(GKResponseFailure)failure
{
    AFHTTPSessionManager *manager = [self getAFNManager];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSURLSessionDataTask *sessionTask = nil;
    if (type == GKRequestTypeGet) { // get请求
        sessionTask = [manager GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            success ?success(responseObject): nil;
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            // 请求成功删除操作
            [[self tasks] removeObject:sessionTask];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            failure ? failure(error) : nil;
        }];
    }else { // 发送post请求
       sessionTask = [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            success ?success(responseObject): nil;
           
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            failure ? failure(error) : nil;
            // 请求失败删除操作
            [[self tasks] removeObject:sessionTask];
        }];
    }
    [[self tasks] addObject:sessionTask];
    return sessionTask;
}

+ (void)Upload:(NSString *)urlString params:(NSDictionary *)params uploadParam:(GKUploadParams *)uploadParam success:(GKResponseSuccess)success failure:(GKResponseFailure)failure
{
    // 创建请求管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
   NSURLSessionDataTask *sessionTask = [manager POST:urlString parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) { // 上传的文件全部拼接到formData
        /**
         *  FileData:要上传的文件的二进制数据
         *  name:上传参数名称
         *  fileName：上传到服务器的文件名称
         *  mimeType：文件类型
         */
         [formData appendPartWithFileData:uploadParam.data name:uploadParam.name fileName:uploadParam.fileName mimeType:uploadParam.mimeType];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 请求失败删除操作
        [[self tasks] removeObject:sessionTask];
        success ?success(responseObject): nil;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         failure ? failure(error) : nil;
        // 请求失败删除操作
        [[self tasks] removeObject:sessionTask];
    }];
    
    [[self tasks] addObject:sessionTask];
}


#pragma makr - 开始监听网络连接

- (void)startMonitoring
{
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        switch (status)
        {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                [GKNetworkingManager sharedManager].networkStatus = GKNetworkStatusUnknown;
                break;
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                [GKNetworkingManager sharedManager].networkStatus = GKNetworkStatusNotReachable;
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                [GKNetworkingManager sharedManager].networkStatus = GKNetworkStatusReachableViaWWAN;
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                
                [GKNetworkingManager sharedManager].networkStatus = GKNetworkStatusReachableViaWiFi;
                break;
        }
    }];
    [mgr startMonitoring];
}
/**
 *  获取html源码
 *
 *  @param urlString url
 *  @param success   请求成功的回调
 *  @param failure   请求失败的回调
 */
+ (void)getHtmlCodeWithUrlString:(NSString *)urlString success:(void (^)(NSData *data))success failure:(void(^)(NSError *error))failure;
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    AFHTTPSessionManager *manager = [self getAFNManager];
    
    [manager GET: urlString parameters: nil progress: nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success)
        {
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure)
        {
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            failure(error);
        }
    }];
}

+ (void)cancelAllTask
{
    [[self tasks] makeObjectsPerformSelector:@selector(cancel)];
}
#pragma mark - 网络监测相关

- (BOOL)isReachable {
    return [self isReachableViaWWAN] || [self isReachableViaWiFi];
}

- (BOOL)isReachableViaWWAN {
    return self.networkStatus == GKNetworkStatusReachableViaWWAN;
}

- (BOOL)isReachableViaWiFi {
    return self.networkStatus == GKNetworkStatusReachableViaWiFi;
}


@end